<template>
    <div class="auth-page">
      <main class="auth-container">
        <form class="auth-form" @submit.prevent="handleRegister">
          <h2>手机号注册</h2>
          
          <!-- 手机号输入 -->
          <div class="form-group">
            <div class="input-wrapper">
              <img src="/icon/register/icon1.png" class="input-icon">
              <input
                v-model="form.username"
                type="tel"
                placeholder="请输入手机号"
                maxlength="11"
                @blur="validateField('username')"
              >
            </div>
            <span v-if="errors.username" class="error">{{ errors.username }}</span>
          </div>
  
          <!-- 密码输入 -->
          <div class="form-group">
            <div class="input-wrapper">
              <img src="/icon/register/icon2.png" class="input-icon">
              <input
                v-model="form.password"
                type="password"
                placeholder="请输入密码（6-20位字母+数字）"
                @blur="validateField('password')"
              >
            </div>
            <span v-if="errors.password" class="error">{{ errors.password }}</span>
          </div>
  
          <!-- 身份证验证 -->
          <div class="form-group">
            <div class="input-wrapper">
              <img src="/icon/register/icon3.png" class="input-icon">
              <input
                v-model="form.card"
                type="text"
                placeholder="身份证后四位"
                maxlength="4"
                @blur="validateField('card')"
              >
            </div>
            <span v-if="errors.card" class="error">{{ errors.card }}</span>
          </div>
  
          <button type="submit" class="submit-btn">注册</button>
  
          <div class="auth-footer">
            已有账号？<NuxtLink :to="localePath('/login')">立即登录</NuxtLink>
          </div>
        </form>
      </main>
    </div>
  </template>
  
  <script setup>
  import { sm2 } from 'sm-crypto' // 添加sm-crypto导入
  import Base64 from 'crypto-js/enc-base64';
  import Hex from 'crypto-js/enc-hex';
  const { $fetchGov } = useNuxtApp()
  const router = useRouter()
  const localePath = useLocalePath()

  definePageMeta({
    layout: 'login-layout'
  })
  const { data:sm2Key } = await useAsyncData(
    'sm2Key',
    () => $fetchGov('/app/api/env/client-public-key', {
      method: 'GET',
      params: {
        _t: Date.now()
      }
    })
  )

  const form = reactive({
    username: '',
    password: '',
    card: ''
  })
  
  const errors = reactive({
    username: '',
    password: '',
    card: ''
  })
  
  // 验证规则集合
  const validators = {
    username: () => {
      if (!form.username) return '手机号不能为空'
      if (!/^1[3-9]\d{9}$/.test(form.username)) return '手机号格式不正确'
      return ''
    },
    password: () => {
      if (!form.password) return '密码不能为空'
      if (form.password.length < 6 || form.password.length > 20) 
        return '密码长度6-20位'
      if (!/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(form.password))
        return '需包含字母和数字'
      return ''
    },
    card: () => {
      if (!form.card) return '身份证后四位不能为空'
      if (!/^\d{3}[0-9Xx]$/.test(form.card)) return '请输入3位数字+身份证末位（如X）'
      return ''
    }
  }
  
  // 单个字段验证
  const validateField = (field) => {
    errors[field] = validators[field]()
  }
  
  // 提交验证
  const validateAll = () => {
    return Object.keys(validators).every(field => {
      errors[field] = validators[field]()
      return !errors[field]
    })
  }
  
  const handleRegister = async () => {
    if (!validateAll()) return

    if (!sm2Key.value?.data) {
      return
    }
    try {
      const encryptedPassword = Base64.stringify(Hex.parse('04' + sm2.doEncrypt(form.password, sm2Key.value.data, 1)))
      const { data:responseData } = await $fetchGov('/app/api/user', {
        method: 'POST',
        body: {
          ...form,
          password: encryptedPassword // 替换为加密后的密码
        },
        server: process.server, // 确保在服务器端执行
      });
      if(responseData.status === 0){
        ElMessage.success('注册成功')
        setTimeout(() => {
          router.push(
            localePath({
              path: `/Login`
            })
          )
        }, 1000);
      }else{
        ElMessage.error(responseData.message)
      }
    } catch (err) {
      console.error('注册失败:', err)
    }
  }
  </script>
  
  <style lang="scss" scoped>
  @use '@/assets/scss/login/index' as *;
  </style>